﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using System.Configuration;

namespace PubSubPublisher
{
    public partial class Publisher
    {
        Socket _client;
        EndPoint _remoteEndPoint;
        
        string _command = "Publish";
        string _topic;
        string _data;

        private IPAddress _serverIPAddress;
        private int _serverPort;

        public IPAddress ServerIPAddress
        {   
            get {return _serverIPAddress;}
            set {_serverIPAddress = value;}
        }

        public int ServerPort
        {
            get { return _serverPort; }
            set { _serverPort = value; }
        }
        
        public Publisher(string ipAddress, int port)
        {            
            //string serverIP = ConfigurationSettings.AppSettings["ServerIP"];
            //IPAddress serverIPAddress = IPAddress.Parse(serverIP);
            //int serverPort = Convert.ToInt32(ConfigurationSettings.AppSettings["ServerPort"]);

            //_serverIPAddress = IPAddress.Parse("127.0.0.1");// ReturnMachineIP(); if you need machine ip then use this method.  
            _serverIPAddress = IPAddress.Parse(ipAddress);
            //_serverPort = 10003;
            _serverPort = port;

            _client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            _remoteEndPoint = new IPEndPoint(_serverIPAddress, _serverPort);
        }

        public void SendASingleData(string topic, string data)
        {
            _topic = topic;
            _data = data;

            string message = _command + "," + topic + "," + data;
            _client.SendTo(Encoding.ASCII.GetBytes(message), _remoteEndPoint);
        }
    }
}
